﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using ZilLion.Service.Core.Ioc;
using ZilLion.Service.ZilLionOss.Domain.Repositorys.Interface;

namespace ZilLion.Service.ZilLionOss.Controllers
{
    public class ComponentLoader : ComponentLoaderBase, IComponentLoader
    {
        

        public override void ConfigureSpecialRoute(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute(
                "OssGateway",
                "Api/OssGateway/{modulekey}/{*path}",
                new { controller = "OssGatewayProxy", action = "RedirectToRealApi" });
        }

        public override Dictionary<string, string> InterceptJwtpayload(Dictionary<string, string> formpayload)
        {
            if (formpayload.ContainsKey("email") && formpayload.ContainsKey("password"))
            {
                var username = formpayload["email"];
                var password = formpayload["password"];

                var pwdrepository = IocContainer.Resolve<IOssUserPwdRepository>();
                var useinforepository = IocContainer.Resolve<IOssUserInfoRepository>();

                if (pwdrepository != null)
                {
                    var pwd = pwdrepository.GetPwdEntity(username);

                    if (pwd != null)
                        if (password == pwd.Userpwd)
                            if (useinforepository != null)
                            {
                                var useinfo = useinforepository.GetUserInfo(username);
                                var result = new Dictionary<string, string>();
                                foreach (var prop in useinfo.GetType().GetProperties())
                                    if (result.ContainsKey(prop.Name.ToLower()))
                                        result[prop.Name.ToLower()] = useinfo.GetPropertyValue(prop.Name).ToString();
                                    else
                                        result.Add(prop.Name.ToLower(), useinfo.GetPropertyValue(prop.Name).ToString());

                                result.Remove("password"); //移除密码信息
                                return result;
                            }
                }
            }


            return null;
        }

        public override void Register(ContainerBuilder builder)
        {
            base.Register(builder);

            #region 注册组件

            RegisterAssemblis(Assembly.Load("ZilLion.Service.ZilLionOss.Domain"));

            #endregion
        }

     
    }
}